package com.bj58.data.emailreports.controllers;

import java.io.File;
import java.io.FileInputStream;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import com.bj58.data.emailreports.dao.CommonDao;
import com.bj58.data.emailreports.dao.SrcDbPool.DBType;
import com.bj58.data.emailreports.model.partnershipModel;
import com.bj58.data.emailreports.service.PartnershipService;
import com.bj58.data.emailreports.utils.DateUtil;
import com.bj58.data.emailreports.utils.EmailReportUtil;
import com.bj58.data.emailreports.utils.MailUtil;
import com.bj58.data.emailreports.utils.ResourcesUtil;
import com.bj58.data.emailreports.utils.SortUtil;
import com.bj58.data.emailreports.utils.TemplateMethodFactory;
import com.bj58.data.emailreports.utils.VelocityTools;
import com.bj58.groupbuy.service.locator.ServiceLocator;
import com.bj58.groupbuy.util.PathUtil;

public class PartnershipReportController {
	
	private PartnershipService partnershipService = ServiceLocator.get(PartnershipService.class);
	private EmailReportUtil erutil = new EmailReportUtil();
	private CommonDao comDao = new CommonDao();

	//限制今昨两天的uv之和小于两万
	public List<String> limituv(List<String> list)
	{		
		List<String> ResultList=new ArrayList<String>();
		for(String temp:list)
		{
			String[] s=temp.split(";");
			
			String a=s[1];
			String[] aa=a.split(",");
			a="";
			for(String t:aa)
			{
				a=a+t;
			}
			
			String b=s[2];
			String[] bb=b.split(",");
			b="";
			for(String t:bb)
			{
				b=b+t;
			}
			
			int total=0;
			if(a.equals("--"))
			{
				total+=0;
			}
			else total+=Integer.parseInt(a);
			if(b.equals("--"))
			{
				total+=0;
			}
			else total+=Integer.parseInt(b);
			
			if(total>=20000)
			{
				ResultList.add(temp);
			}				
		}	
		return ResultList;
	}
	
	/*合作方日报
	 */
	public String partnershipReport(String searchDate)throws Exception{
		
		try {
			//velocity对象
			VelocityContext context = new VelocityContext();
			Object tools = TemplateMethodFactory.getInstance(VelocityTools.class);
			context.put("tools",tools);
			
			//读取模板内容
			String filepath =PathUtil.getWFNamespaceFolder()+"/emailtemp/PartnershipReport.html";
			ResourcesUtil.setCharset(Charset.forName("utf-8"));
			FileInputStream inputStream = new FileInputStream(new File(filepath));
			String templateContext = ResourcesUtil.readString2(inputStream);
			inputStream.close();
			
			Date  sDate = DateUtil.strToDate(searchDate, "yyyy-MM-dd");
			String nowDate = DateUtil.getStringDate(sDate,"yyyy-MM-dd");
			String lastDate = DateUtil.getStringDate(DateUtil.getDateBefore(sDate, 1),"yyyy-MM-dd");
			String lastWeek = DateUtil.getStringDate(DateUtil.getDateBefore(sDate, 7),"yyyy-MM-dd");
			context.put("nowDate",nowDate);
			context.put("lastDate",lastDate);
			context.put("lastWeek",lastWeek);
			
			//日期map
			Map<String,String> dateMap = new HashMap<String, String>();
			dateMap.put("nowDate",nowDate);
			dateMap.put("lastDate", lastDate);
			dateMap.put("lastWeek",lastWeek);
			List<String> dateList = new ArrayList<String>();
			dateList.add(nowDate);dateList.add(lastDate);dateList.add(lastWeek);
					
			//数据源检查
			for(String d:dateList)
			{
				String sql = "select count(1) from t_netflow_source_ROImonitor  where stat_date = '"+d+"'";
				int count = comDao.countAll(sql, DBType.db_94_data_app.getValue());
				if(count==0)
				{
					throw new Exception("日期："+d+" 数据为空");
				}
			}
					
			List<String> showCols = new ArrayList<String>(); //同比环比计算指标集
			List<String> percentList = new ArrayList<String>();//百分比指标集

			showCols.clear();
			showCols.add("uv");showCols.add("pv");showCols.add("vppv");showCols.add("vppv_uv");showCols.add("out_rate");showCols.add("info_count");showCols.add("cpc_uv");
			showCols.add("ROI");showCols.add("cpc_cash");showCols.add("zhineng_cash");showCols.add("zhaopin_vppv");showCols.add("fangchan_vppv");showCols.add("ershouche_vppv");showCols.add("ershou_vppv");showCols.add("huangye_vppv");			
			
			percentList.clear();
			percentList.add("out_rate");

			//PC端联盟合作方
			String platform ="-1";
			List<partnershipModel> lianmengPC = partnershipService.getLianmengData(platform,nowDate,lastDate,lastWeek);			
			if(lianmengPC == null || lianmengPC.isEmpty())
				throw new NullPointerException("PC端联盟合作方数据为空");
			
			List<String> lianmengPCList = erutil.conformDataTypeSeven(lianmengPC, partnershipModel.class, "source", showCols, "statDate", percentList, dateList);		
			lianmengPCList = SortUtil.sortListByFileName(lianmengPCList, 1, 2);
			lianmengPCList=limituv(lianmengPCList);	
			context.put("lianmengPCList",lianmengPCList);	
			
			//M端联盟合作方       
			platform ="0";
			List<partnershipModel> lianmengM = partnershipService.getLianmengData(platform,nowDate,lastDate,lastWeek);
			if(lianmengM == null || lianmengM.isEmpty())
				throw new NullPointerException("M端联盟合作方数据为空");
			
			List<String> lianmengMList = erutil.conformDataTypeSeven(lianmengM, partnershipModel.class, "source", showCols, "statDate", percentList, dateList);		
			lianmengMList = SortUtil.sortListByFileName(lianmengMList, 1, 2);
			lianmengMList=limituv(lianmengMList);	
			context.put("lianmengMList",lianmengMList);	
			
			//PC端在线市场   
			platform ="-1";
			List<partnershipModel> onlineMakectPC = partnershipService.getonlineMakectData(platform,nowDate,lastDate,lastWeek);	
			if(onlineMakectPC == null || onlineMakectPC.isEmpty())
				throw new NullPointerException("PC端在线市场  ");
			
			List<String> onlineMakectPCList = erutil.conformDataTypeSeven(onlineMakectPC, partnershipModel.class, "source", showCols, "statDate", percentList, dateList);		
			onlineMakectPCList = SortUtil.sortListByFileName(onlineMakectPCList, 1, 2);
			onlineMakectPCList=limituv(onlineMakectPCList);	
			context.put("onlineMakectPCList",onlineMakectPCList);	
				
			//M端在线市场    
			platform ="0";
			List<partnershipModel> onlineMakectM = partnershipService.getonlineMakectData(platform,nowDate,lastDate,lastWeek);	
			if(onlineMakectM == null || onlineMakectM.isEmpty())
				throw new NullPointerException("M端在线市场  ");
			
			List<String> onlineMakectMList = erutil.conformDataTypeSeven(onlineMakectM, partnershipModel.class, "source", showCols, "statDate", percentList, dateList);		
			onlineMakectMList = SortUtil.sortListByFileName(onlineMakectMList, 1, 2);
			onlineMakectMList=limituv(onlineMakectMList);	
			context.put("onlineMakectMList",onlineMakectMList);	
			
			VelocityEngine velocity  = new VelocityEngine();
			Velocity.setProperty("input.encoding", "utf-8");
			Velocity.setProperty("output.encoding", "utf-8");
			String content = templateContext;
			StringWriter out = new StringWriter();
			try {
					velocity.evaluate(context, out, "", content);
			} catch (Exception e) {            
				e.printStackTrace();
			}
			content = out.toString();
			out.close();
			return content;
		} catch (Exception e) {
			throw e;
		}
	}
	
	public static void main(String[] args) {
		PartnershipReportController  wk = new PartnershipReportController();
		String searchDate = "2016-01-05";
		String context;
		try {	
			context = wk.partnershipReport(searchDate);
			MailUtil.javaMailSend("合作方日报测试" + searchDate, context, "guoxue@58.com",null);			
			
		} catch (Exception e) {
			e.printStackTrace();
			String errorinfo=e.getMessage();
			MailUtil.javaMailSend("合作方日报测试报错" + searchDate, errorinfo, "guoxue@58.com",null);	
		}
	}
}
